package com.wuwei.elearning.question.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuwei.elearning.dto.ConversionMessage;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.messageQueen.Message;
import com.wuwei.elearning.messageQueen.MessageQueue;
import com.wuwei.elearning.question.domain.Subject;
import com.wuwei.elearning.question.domain.Video;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.mapper.VideoMapper;
import com.wuwei.elearning.question.service.VideoService;
import com.wuwei.elearning.service.CacheService;
import com.wuwei.elearning.utils.MinioUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {


    @Resource
    private MinioUtil minioUtil;

    @Resource
    private VideoMapper videoMapper;


    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadVideo(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        Video video = new Video();
        video.setName(originalFilename);
        videoMapper.insert(video);
//        conversionProducer.sendConversionTaskForVideo(KafkaConfig.VIDEO_CONVERSION_TOPIC, originalFilename,file, video.getId());
        // 1. 先将文件上传到MinIO
        String tempPath = "temp/" + originalFilename;
        minioUtil.uploadToPath(file,tempPath);

        // 2. 只发送元数据到Kafka
        Message message = new Message();
        message.setFileName(originalFilename);
        message.setId(video.getId());
        message.setMinioPath(tempPath); // 存储MinIO中的路径，而不是文件内容
        messageQueue.send(Constant.VIDEO_CONVERSION_TOPIC, message,video.getId());
    }

    @Autowired
    private MessageQueue messageQueue;

    // 查询时使用缓存
    @Override
    public List<Video> selectList(String name, int currentPage, int pageSize) {
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"_".equals(name),Video::getName,name);
        IPage<Video> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<Video> questionIPage = videoMapper.selectPage(page, wrapper);
        List<Video> videos = questionIPage.getRecords();
        for (Video video : videos) {
            String upload = video.getUrl();
            // 构建Redis键
            String redisKey = Constant.MINIO_VIDEO + upload;
            // 尝试从Redis获取
            String url = cacheService.getPdf(upload, redisKey);
            video.setUrl(url);
        }
        return videos;
    }

    // 查询时使用缓存
    @Override
    public Long selectTotal(String name) {
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(!"_".equals(name),Video::getName,name);
        Long count = videoMapper.selectCount(wrapper);
        return count;
    }

    // 删除视频时删除缓存
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByUrl(Video video) {
        log.info("即将删除的video-{}",video.getName());
        Video selectedById = videoMapper.selectById(video.getId());
        String objectName = selectedById.getUrl();
        minioUtil.remove(objectName);
        // 构建Redis键
        String redisKey = Constant.MINIO_VIDEO + objectName;
        cacheService.delete(redisKey);
        videoMapper.deleteById(video.getId());
        List<Subject> subjects = subjectMapper.findAllLeafs();
        for (Subject subject : subjects) {
            String videos = subject.getVideos();
            if (videos!=null) {
                List<Long> videoList = JSON.parseArray(videos, Long.class).stream().filter(id->!id.equals(video.getId())).collect(Collectors.toList());
                subject.setVideos(JSON.toJSONString(videoList));
                subjectMapper.updateById(subject);
            }
        }
    }


    @Resource
    private SubjectMapper subjectMapper;

    @Resource
    private CacheService cacheService;

    // 查询时使用缓存
    @Override
    public List<Video> getAll() {
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        List<Video> Videos = videoMapper.selectList(wrapper);
        return Videos;
    }

    // 查询时使用缓存
    @Override
    public Long selectCount(String fileName) {
        LambdaQueryWrapper<Video> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Video::getName,fileName);
        return videoMapper.selectCount(wrapper);
    }

//    @Async
//    protected void processVideoAsync(File tempFile, String fileName, String url) {
//        try {
//            // 获取视频长度
//            long duration = extractVideoDuration(tempFile);
//            Video video = new Video();
//            video.setUrl(url);
//            video.setName(fileName);
//            video.setDuration(duration);
//            videoMapper.insert(video);
//            log.info("视频处理完成: {}", fileName);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("视频处理失败");
//        } finally {
//            if (tempFile.exists()) {
//                tempFile.delete();
//            }
//        }
//    }



}
